<template>
	<view style="background-color: #fff;" >
		<view class="remark" v-if="form.remark">
			<u-alert type="error" :show-icon="true" :title="'拒绝原因 :'+form.remark"></u-alert>
		</view>
		<image src="@/static/img/1.png" mode="widthFix" style="width: 100%; display: block;"></image>
		<view style="position: relative;">
			<image src="@/static/img/2.png" mode="widthFix" style="width: 416rpx; display: block; margin: 0 auto;">
			</image>
			<text
				style="position: absolute; font-size: 16px; color: #fff; width: 416rpx; left: 50%; margin-left: -208rpx; text-align: center; top: 12rpx;">代理商入驻信息</text>
		</view>
		<view style="padding: 0 40rpx;">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth='100'>

				<u-form-item label="申请代理商" prop="roleId" borderBottom>
					<u-radio-group v-model="form.roleId" placement="column" activeColor="#9F2B45">
						<u-radio :customStyle="{marginBottom: '8px'}" v-if="superiorsData.level<=1" label="招商" :name="3"></u-radio>
						<u-radio :customStyle="{marginBottom: '8px'}" v-if="superiorsData.level<=2"  label="经销商" :name="4"></u-radio>
						<u-radio :customStyle="{marginBottom: '8px'}" v-if="superiorsData.level<=3"  label="批发商" :name="5"></u-radio>
						<u-radio :customStyle="{marginBottom: '8px'}" label="团购" :name="6"></u-radio>
					</u-radio-group>
				</u-form-item>

				<u-form-item prop="businessLicense" label="上传营业执照" borderBottom>
					<u-upload accept="image" @afterRead="afterRead(1,$event)"
						@delete="(event, type) => deletePic(event, 1)" multiple :maxCount="1" width="210rpx"
						height="210rpx" :fileList="businessLicense" :sizeType="['compressed']"></u-upload>
				</u-form-item>

				<u-form-item label="身份证正面" prop="cardFrontImg" borderBottom  v-if="!userInfo.realName" >
					<!-- #ifdef MP-WEIXIN -->
					<ocr-navigator @onSuccess="ocrSuccess" certificateType="idCard" :opposite="false"
						style="width: 315rpx; height: 202rpx;">
						<view class="back">
							<image src="/static/img/3.png" style="width: 315rpx; height: 202rpx;"
								v-if="!form.cardFrontImg"></image>
							<image :src="form.cardFrontImg" style="width: 110px;height: 110px;" v-if="form.cardFrontImg"
								mode=""></image>
						</view>
					</ocr-navigator>
					<!-- #endif -->
					<!-- #ifdef APP-PLUS-->
					<u-upload :capture="['album', 'camera']" accept="image" @afterRead="afterRead(1, $event)"
						@delete="deletePic(1,$event)" multiple :maxCount="1" width="210rpx" height="210rpx"
						:fileList="rightSide" :sizeType="['compressed']">
					</u-upload>
					<!--  #endif -->
				</u-form-item>

				<u-form-item label="身份证背面" prop="cardReverseImg" borderBottom  v-if="!userInfo.realName" >

					<!-- #ifdef MP-WEIXIN -->
					<ocr-navigator @onSuccess="ocrSuccess" certificateType="idCard" :opposite="true"
						style="width: 315rpx; height: 202rpx;">
						<view class="back">
							<image src="/static/img/4.png" style="width: 315rpx; height: 202rpx;"
								v-if="!form.cardReverseImg"></image>
							<image :src="form.cardReverseImg" style="width: 110px;height: 110px;"
								v-if="form.cardReverseImg" mode=""></image>
						</view>
					</ocr-navigator>
					<!-- #endif -->
					<!-- #ifdef APP-PLUS-->
					<u-upload :capture="['album', 'camera']" accept="image" @afterRead="afterRead(2,$event)"
						@delete="deletePic(2,$event)" multiple :maxCount="1" width="210rpx" height="210rpx"
						:fileList="ReverseSide" :sizeType="['compressed']">
					</u-upload>
					<!--  #endif -->
				</u-form-item>

				<u-form-item label="推荐人" prop="referrerId">
					<view class="Grid Grid--center">
						<u--input v-model="referrerId" border="none" style="display: none;"></u--input>
						<image :src="superiorsData.avatar" style="width: 62rpx; height: 62rpx;"></image>
						<view style="font-size: 12px; padding: 0 10rpx;">{{superiorsData.nickname}}</view>
						<view>{{superiorsData.phone}}</view>
					</view>
				</u-form-item>

				<view class="uni-btn-v">
					<view style="margin-bottom: 20rpx;">
						<u-button @click="submit" type="primary" shape="circle" color="#9F2B45" :loading="isLoading"
							loadingText="提交中..." text="提交审核"></u-button>
					</view>
					<view style="margin-bottom: 20rpx;">
						<u-button @click="reset" shape="circle" text="重置表单"></u-button>
					</view>
				</view>

			</u--form>
		</view>
	</view>

</template>

<script>
	import {
		customUpdateAvatar
	} from "@/utils/customUpdateAvatar"
	// 申请成为代理商
	import {
		MerchantStore,
		applicationRecord,
		superiors
	} from "@/api/user";
	import {
		VUE_APP_API_URL
	} from "@/config";
	import cookie from "@/utils/store/cookie";
	import {
		mapGetters
	} from "vuex";
	import { login } from "@/utils/index";
	export default {
		data() {
			return {
				isLoading: false,
				rules: {
					'roleId': {
						type: 'number',
						required: true,
						message: '请选择代理商',
						trigger: ['blur', 'change']
					},
					'businessLicense': {
						type: 'string',
						required: true,
						message: '请上传营业执照',
						trigger: ['blur', 'change']
					},
					'cardFrontImg': {
						type: 'string',
						required: true,
						message: '请上传身份证正面',
						trigger: ['blur', 'change']
					},
					'cardReverseImg': {
						type: 'string',
						required: true,
						message: '请上传身份证背面',
						trigger: ['blur', 'change']
					}
				},
				form: {
					roleId: "", // 角色id
					businessLicense: "", // 营业执照
					state: "",
					remark: "",
					referrerId: "", //推荐人id
					realName: "",
					cardId: "",
					cardFrontImg: "",
					cardReverseImg: ""
				},
				businessLicense: [], //营业执照
				keys: ``,
				superiorsData:{},
				type: ''
			};
		},
		computed: mapGetters(["userInfo"]),
		mounted() {
			this.getInfo()
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			this.$refs.form.setRules(this.rules)
		},
		onLoad(options) {
			console.log(options)
			if (Object.keys(options).length) {
				// 获取太阳码中shopId和uid
				this.form.referrerId = options.scene
				// 根据推荐人id获取推荐人用户信息
				this.initData()
				// 设置uid
				cookie.set("spread", this.form.referrerId);
				// 授权登录
				// #ifdef MP-WEIXIN
				login().finally(() => {});
				// #endif
			}
		},
		onShow() {},
		methods: {
			initData() {
				console.log('this.form.referrerId',this.form.referrerId)
				superiors(this.form.referrerId).then(res=>{
					this.superiorsData=res.data
				})
			},
			parseQuery(path) {
				let res = {};
				
				const query = (path || "")
					.trim()
					.replace(/^(\?|#|&)/, "");
				if (!query) {
					return res;
				}
				
				query.split("&").forEach(param => {
					console.log(param)
					const parts = param.replace(/\+/g, " ").split("=");
					const key = decodeURIComponent(parts.shift());
					const val = parts.length > 0 ? decodeURIComponent(parts.join("=")) : null;
				
					if (res[key] === undefined) {
						res[key] = val;
					} else if (Array.isArray(res[key])) {
						res[key].push(val);
					} else {
						res[key] = [res[key], val];
					}
				});
				return res
			},
			
			async ocrSuccess(e) {
				console.log(e, 'e')
				if (!e.detail.type) {
					this.form.realName = e.detail.name.text
					this.form.cardId = e.detail.id.text
				}
				const result = await customUpdateAvatar(e.detail.image_path);
				!e.detail.type ? this.form.cardFrontImg = result : this.form.cardReverseImg = result
			},
			reset() {
				this.form = this.$options.data().form;
				this.image = []
				this.carouselMap = []
				this.businessLicense = []
				this.otherQualifications = []
			},
			submit() {
				let that = this

				this.form.businessLicense = this.businessLicense[0].url
				if (this.userInfo.realName) {
					delete 	this.form.cardId
					delete 	this.form.realName
					delete this.form.cardFrontImg
					delete this.form.cardReverseImg
				} 
				this.$refs.form.validate().then(res => {
					this.isLoading = true
					MerchantStore(this.form).then(res => {
						this.isLoading = false
						uni.showToast({
							title: '资料已提交，请耐心等待审核结果~',
							icon: "none"
						});

						setTimeout(() => {
							that.$yrouter.reLaunch({
								path: "/pages/launch/index",
								query: {
									type: 'User'
								}
							});
						}, 4000);
					}).catch(err => {
						uni.showToast({
							title: err.msg,
							icon: "none"
						});
						this.isLoading = false
					})


				}).catch(errors => {
					uni.$u.toast('请完善必填项')
				})
			},
			getInfo() {
				const that=this
				uni.showLoading({
					title: "加载中",
				});
				applicationRecord().then(res => {
					if(res.data=="BOUND"){
						uni.showToast({
							title: '已绑定上级，如需修改上级请联系负责人"',
							icon: "none"
						});
						setTimeout(() => {
							that.$yrouter.reLaunch({
								path: "/pages/launch/index",
								query: {
									type: 'User'
								}
							});
						}, 4000);
					}
					if(res.data=="UNDER_REVIEW"){
						uni.showToast({
							title: '资料已提交，请耐心等待审核结果~"',
							icon: "none"
						});
						setTimeout(() => {
							that.$yrouter.reLaunch({
								path: "/pages/launch/index",
								query: {
									type: 'User'
								}
							});
						}, 4000);
					}
					
					if (res.data.businessLicense) {
						this.form =res.data
						this.businessLicense = [{url:res.data.businessLicense}]
					}
					
				
					
					// this.image = this.assemblyArr(res.data.image)
					// this.carouselMap = this.assemblyArr(res.data.carouselMap)
					// this.otherQualifications = this.assemblyArr(res.data.otherQualifications)
					uni.hideLoading();
				}).catch(err=>{
					console.log(err)
				}
				)
			},
		
			deletePic({
				index
			}, type) {
				if (type == 1) {
					this.businessLicense.splice(index, 1)
				} else if (type == 2) {
					this.image.splice(index, 1)
				} else if (type == 3) {
					this.carouselMap.splice(index, 1)
				} else {
					this.otherQualifications.splice(index, 1)
				}
			},

			customUpdate(filePath, arr) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: `${VUE_APP_API_URL}/api/qiNiuContent`,
						filePath: filePath,
						name: 'file',
						formData: {
							bucketName: 'bucket2',
							storeFileName: 'file',
							saveSql: '1'
						},
						header: {
							'token': cookie.get('login_status'),
							// 'token': 'a82472c6-96c9-46b0-a018-783dea7864b5',
							'content-type': 'multipart/form-data' // 默认值
						},
						success: uploadFileRes => {
							if (uploadFileRes.statusCode === 200) {
								var dataResult = JSON.parse(uploadFileRes.data).data;
								resolve(dataResult)
							} else {
								arr.splice(arr.length - 1, 1)
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
							}
						},
						fail() {
							arr.splice(arr.length - 1, 1)
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					})
				})
			},
			// 新增图片
			async afterRead(status, event) {
				let arr
				if (status == 1) {
					arr = this.businessLicense
				} else if (status == 2) {
					arr = this.image
				} else if (status == 3) {
					arr = this.carouselMap
				} else {
					arr = this.otherQualifications
				}

				let lists = [].concat(event.file)

				// 记录图片数组起点索引
				let fileListLen = arr.length

				lists.map((item) => {
					arr.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.customUpdate(lists[i].url, arr)
					let item = arr[fileListLen]
					arr.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result[0],
						filePath: result[0]
					}))
					fileListLen++
				}

			},

			imageArrSalvage(arr) {
				if (arr.length <= 0) return ''
				let Array = []
				for (var i = 0; i < arr.length; i++) {
					Array.push(arr[i].url)
				}
				return Array.join(',')
			}
		},
	};
</script>
<style>
	.back {
		width: 315rpx;
		height: 202rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 8px 8px 0;
		box-sizing: border-box;
	}
</style>